package com.multysite.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.NamespaceManager;
import com.multysite.entity.News;
import com.multysite.entity.admin.ApplicationConfig;
import com.multysite.entity.admin.ApplicationTemplate;
import com.multysite.model.CategoryModel;
import com.multysite.model.NewsModel;
import com.multysite.model.TagModel;
import com.multysite.quercus.CompileScriptEngine;
import com.multysite.util.RecentViewHelper;
import com.multysite.util.Setting;

@SuppressWarnings("serial")
public class DetailServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(DetailServlet.class
			.getName());

	private static TreeMap<String, String> treeCache = new TreeMap<String, String>();

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			ApplicationTemplate template = (ApplicationTemplate) req
					.getAttribute("template");
			ApplicationConfig config = (ApplicationConfig) req
					.getAttribute("config");
			if (template != null && config != null) {
				/*
				 * get detail content
				 */
				String alias = req.getRequestURI().replace("/", "")
						.replace(".html", "");
				alias = URLDecoder.decode(alias, "UTF-8");
				if (treeCache.containsKey(alias)) {
					log.warning("-------detail cached -----");
					resp.getWriter().print(treeCache.get(alias));
				} else {
					log.warning("-------detail no cache -----");
					News obj = NewsModel.getById(alias);
					if (obj != null) {
						CategoryModel cateModel = new CategoryModel();
						cateModel.prepareAll();
						TagModel tagModel = new TagModel();
						tagModel.prepareList();
						CompiledScript compiledscript = CompileScriptEngine
								.getCompileScript(config.getApplicationId(),
										"detail", template.getDetail());

						Bindings bind = compiledscript.getEngine().getBindings(
								ScriptContext.ENGINE_SCOPE);
						bind.put("title_for_layout", config.getTitle());
						bind.put("description_for_layout",
								config.getDescription());
						bind.put("keyword_for_layout", config.getKeyword());
						bind.put("css_for_layout", template.getCss());
						bind.put("js_for_layout", template.getJs());

						RecentViewHelper.addRecentView(obj);
						bind.put("recent_view",
								RecentViewHelper.getRecentView());
						bind.put("list_tag", tagModel.getListResult());
						bind.put("list_category", cateModel.getListResult());
						bind.put("article", obj);
						try {
							String result = (String) compiledscript.eval();
							treeCache.put(alias, result);
							resp.getWriter().print(result);
						} catch (Exception e) {
							e.printStackTrace();
							log.warning(e.toString());
						}
					} else {
						resp.sendRedirect("/");
					}
				}

			} else {
				NamespaceManager.set(Setting.getGeneralNamespace());
				resp.sendRedirect("http://" + Setting.getDomain());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.warning(e.toString());
		}
	}
}
